﻿@using Partner.Surround.Web.Startup
@using Partner.Surround.Authorization
@using Partner.Surround.Web.Models.Users
@model UserListViewModel
@{
    ViewBag.CurrentPageName = PageNames.Users;
}

@section styles{
    <link href="~/css/treetable.css" rel="stylesheet" />
    <link href="~/lib/layui-extend-modules/ztree/metroStyle/metroStyle.css" rel="stylesheet" />
    <style>
        .layui-card-header.layui-card-header-auto {
            padding-top: 15px;
            padding-bottom: 5px;
            height: auto;
        }
    </style>
}

<!--用户列表-->
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header layui-card-header-auto">
            <div class="layui-form">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">关键字</label>
                        <div class="layui-input-block">
                            <input type="text" name="filterText" placeholder="请输入关键字" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button class="layui-btn layui-btn-user" lay-submit lay-filter="LAY-user-front-search">
                            <i class="layui-icon layui-icon-search layui-button-btn"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-card-body">
            <div class="layui-btn-container">
                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Delete))
                {
                    <button class="layui-btn layui-btn-user" data-type="batchdel">删除</button>
                }
                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Create))
                {
                    <button class="layui-btn layui-btn-user" data-type="add">添加</button>
                }
            </div>
            <div class="layui-row">
                <div class="layui-col-md2 layui-col-xs12">
                    <ul id="tree" class="ztree" style="padding: 0px; border: 1px solid #ddd; overflow: auto;"></ul>
                </div>
                <div class="layui-col-md10 layui-col-xs12">
                    <table class="layui-table"
                           lay-data="{height: 'full-180', page:true, id:'userList'}"
                           lay-filter="userList" lay-size="xs">
                        <thead>
                            <tr>
                                <th lay-data="{checkbox:true, fixed: true,width:40}"></th>
                                <th lay-data="{field:'userName'}">用户名</th>
                                <th lay-data="{field:'phoneNumber'}">手机号</th>
                                <th lay-data="{field:'roles',templet:'#setRoleNames'}">角色</th>
                                @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_ResetPassword) ||
                                await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Update) ||
                                await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Delete))
                                {
                                    <th lay-data="{fixed:'right', align:'center', toolbar: '#userBarList'}"></th>
                                }
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!--列表按钮-->
<script type="text/html" id="userBarList">
    <div class="layui-table-cell laytable-cell-1-0-9">
        @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_ResetPassword))
        {
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="restPassword"><i class="layui-icon layui-icon-edit"></i>重置密码</a>
        }
        @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Update))
        {
            <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
        }
        @if (await PermissionChecker.IsGrantedAsync(PermissionNames.Pages_Frame_Users_Delete))
        {
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
        }
    </div>
</script>

<!--角色拼接-->
<script type="text/javascript">
    var roleNames = function (arr) {
        var sum = '';
        for (var i = 0; i <= arr.length - 1; i++) {
            sum += arr[i].roleName;
            if (i < arr.length - 1) {
                sum += '、';
            }
        }

        return sum;
    };
</script>
<script type="text/html" id="setRoleNames">
    {{ roleNames(d.roles) }}
</script>

@section scripts{
    <script type="text/javascript">
        layui.config({
            base: '/lib/layui-extend-modules/' //静态资源所在路径
        }).extend({
            ztree: 'ztree/ztree'
        }).use(['jquery', 'form', 'ztree', 'table'], function () {
            var $ = layui.$,
                form = layui.form,
                table = layui.table;

            //监听搜索
            form.on('submit(LAY-user-front-search)', function (data) {
                var field = data.field;

                loadUserList(field);//执行重载
            });

            //主列表加载，可反复调用进行刷新
            var config = {};  //table的参数，如搜索key，点击tree的id
            var loadUserList = function (options) {
                if (options != undefined) {
                    $.extend(config, options);
                }
                table.reload('userList', {
                    url: "@Url.Action("GetUserList", "Users")",
                    where: config,
                    parseData: function (res) {
                        return {
                            "code": res.result.code, //解析接口状态
                            "msg": res.result.msg, //解析提示文本
                            "count": res.result.count, //解析数据长度
                            "data": res.result.data //解析数据列表
                        };
                    },
                    response: {
                        statusCode: 200 //规定成功的状态码，默认：0
                    }
                });
            };

            //左边树状机构列表
            var zTree = function () {
                var zTreeObj;
                var setting = {
                    view: { selectedMulti: false },
                    data: {
                        key: {
                            name: 'displayName',
                            title: 'displayName'
                        },
                        simpleData: {
                            enable: true,
                            idKey: 'id',
                            pIdKey: 'parentId',
                            rootPId: 'null'
                        }
                    },
                    callback: {
                        onClick: function (event, treeId, treeNode) {
                            loadUserList({ organizationUnitId: treeNode.id });
                        }
                    }
                };
                var load = function () {
                    abp.ajax({
                        type:"Get",
                        url: "@Url.Action("GetOrganizationUnitList", "OrganizationUnits")"
                    }).done(function (result) {
                        var treeNodes = result.data;
                        var rootNode = { displayName: "根节点", id: null, parentId: "" };
                        treeNodes.push(rootNode);
                        var unAssignedNode = { displayName: "未分配部门", id: -1, parentId: null };
                        treeNodes.push(unAssignedNode);

                        zTreeObj = $.fn.zTree.init($("#tree"), setting);
                        zTreeObj.addNodes(null, treeNodes);
                        zTreeObj.expandAll(true);
                        loadUserList({ organizationUnitId: "" });
                    });
                };
                load();
                return {
                    reload: load
                };
            }();
            $("#tree").height($("div.layui-row").height() - 2);

            //删除用户
            function deleteUser(data) {
                parent.layer.confirm('确定删除吗?', function (index) {
                    var targetUrl ="@Url.Action("DeleteUser", "Users")";
                    abp.ajax({
                        url: targetUrl,
                        data: JSON.stringify(data)
                    }).done(function (data) {
                        if (data.code == 200) {
                            abp.notify.success(data.msg);
                            loadUserList();
                        }
                    }).fail(function (jqXHR) {
                        parent.layer.msg(jqXHR.message, { icon: 5 });
                    }).always(function () {
                        parent.layer.close(index);
                    });
                });
            };

            //创建或更新用户
            function createOrUpdateUser(userData) {
                parent.layer.open({
                    type: 2,
                    title: userData.title,
                    content: userData.content,
                    area: ["710px","436px"],
                    btn: ['确定', '取消'],
                    yes: function(index, layero){
                        parent.window['layui-layer-iframe'+ index].layui.submitForm();
                    }
                });
            }

            //创建或更新完毕回调
            layui.callback = function (data) {
                parent.layer.close(data.index); //关闭弹层
                abp.notify.success(data.msg);
                loadUserList();
            }

            //监听工具条
            table.on('tool(userList)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {   //删除
                    deleteUser([{ "id": data.id }]);
                } else if (obj.event === 'edit') {  //编辑
                    var userData = {
                        title: '编辑用户信息',
                        content: "@Url.Action("CreateOrUpdateUser", "Users")" + "?userId=" + data.id
                    };
                    createOrUpdateUser(userData);
                } else if (obj.event === 'restPassword') {
                    var waitIndex = parent.layer.load(2);
                    abp.ajax({
                        url: "@Url.Action("ResetUserPassword", "Users")",
                        data: JSON.stringify({ "userId": data.id }),
                        abpHandleError: false
                    }).done(function (data) {
                        abp.notify.success(data.msg);
                    }).fail(function (jqXHR) {
                        parent.layer.msg(jqXHR.message, { icon: 5 });
                    }).always(function () {
                        parent.layer.close(waitIndex);
                    });
                }
            });

            //监听页面主按钮操作
            var active = {
                batchdel: function () {
                    var checkStatus = table.checkStatus('userList'),
                        checkData = checkStatus.data; //得到选中的数据

                    if (checkData.length === 0) {
                        return parent.layer.msg('请选择数据');
                    }

                    var ids = checkData.map(function (d) { return { "id": d.id }; });
                    deleteUser(ids);
                },
                add: function () {//添加
                    var userData = {
                        title: '添加用户',
                        content:"@Url.Action("CreateOrUpdateUser", "Users")"
                    };
                    createOrUpdateUser(userData);
                }
            };

            //点击事件转发器
            $('.layui-btn.layui-btn-user').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
        });
    </script>
}


